package com.tvunetworks.center.user.schedule;

import com.tvunetworks.center.user.service.UserInstanceService;
import com.tvunetworks.leader.election.starter.LeaderElection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @program: tvucc-aggregator
 * @description: UserInstanceSchedule
 * @author lebronchen
 * @create: 2020-04-24 13:17
 **/
@Component
@Slf4j
public class UserInstanceSchedule {

    @Autowired
    private UserInstanceService userInstanceService;
    @Autowired
    private LeaderElection leaderElection;

    @Value("${task.enable.remedyUserInstancePeerId}")
    private boolean enableRemedyUserInstancePeerId;
    @Value("${task.enable.syncInstanceStatus}")
    private boolean enableSyncInstanceStatus;
    @Value("${task.enable.sendRunningEmail}")
    private boolean enableSendRunningEmail;

    /**
     * 开关机流程失败导致 TPC 设备需要绑定和释放的补救任务
     */
    @Scheduled(initialDelay = 30000, fixedDelayString = "${task.userInstance.remedyUserInstancePeerId}")
    public void remedyUserInstancePeerId(){
        if (!enableRemedyUserInstancePeerId) {
            return;
        }
        if (!leaderElection.isMaster()) {
            log.info("UserInstanceSchedule remedyUserInstancePeerId leader election not master");
            return;
        }
        userInstanceService.remedyUserInstancePeerId();
    }

    /**
     * 定时查询实例如果被关闭了，修改 UserInstance 为关闭状态
     */
    @Scheduled(initialDelay = 3500, fixedDelayString = "${task.userInstance.syncInstanceStatus}")
    public void syncInstanceStatus() {
        if (!enableSyncInstanceStatus) {
            return;
        }
        if (!leaderElection.isMaster()) {
            log.info("UserInstanceSchedule syncInstanceStatus leader election not master");
            return;
        }
        try {
            userInstanceService.syncInstanceStatus();
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * sendRunningEmail
     */
    @Scheduled(cron = "0 0 12 * * ?")
    public void sendRunningEmail(){
        log.error("sendRunningEmail in");
        if (!enableSendRunningEmail) {
            return;
        }
        log.error("sendRunningEmail enable");
        if (!leaderElection.isMaster()) {
            log.info("UserInstanceSchedule sendRunningEmail leader election not master");
            return;
        }
        try {
            log.error("UserInstanceSchedule sendRunningEmail start");
            userInstanceService.sendRunningInstanceEmailToSupport();
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
